package com.xky.example_student.controller.file;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xky.example_student.entity.Score;
import com.xky.example_student.service.ScoreService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import jakarta.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/file")
@Tag(name = "文件传输管理")
@Slf4j
public class Filestream {

    @Autowired
    private ScoreService scoreService;


    /**
     * 学生端导出成绩
     *
     * @param name
     * @return
     */
    @PostMapping("/fileOutputStudent")
    @Operation(summary = "学生导出成绩数据到文件")
    public ResponseEntity<byte[]> fileOutputStreamStudent(@RequestParam(required = false) String name, HttpServletRequest request) {
        // 从请求头获取用户信息
        String userRole = request.getHeader("User-Role");
        String userName = request.getHeader("User-Name");
        String userStuId = request.getHeader("User-StuId");
        
        // 对用户名进行URL解码，处理中文字符
        if (userName != null) {
            try {
                userName = java.net.URLDecoder.decode(userName, "UTF-8");
            } catch (Exception e) {
                log.warn("用户名解码失败: {}", userName, e);
            }
        }
        
        log.info("收到导出请求 - 角色: {}, 姓名: {}, 学号: {}", userRole, userName, userStuId);

        // 验证用户权限
        if (!"student".equals(userRole)) {
            log.error("非学生用户请求导出学生成绩");
            return ResponseEntity.status(HttpStatus.FORBIDDEN)
                    .body("无权限访问".getBytes(StandardCharsets.UTF_8));
        }

        // 使用请求头中的用户名，如果没有则使用参数中的name
        String studentName = (userName != null) ? userName : name;
        
        if (studentName == null || studentName.trim().isEmpty()) {
            log.error("学生姓名为空");
            return ResponseEntity.badRequest()
                    .body("学生姓名不能为空".getBytes(StandardCharsets.UTF_8));
        }

        // 根据学号查询成绩
        List<Score> list;
        if (userStuId != null) {
            // 如果有学号，优先使用学号查询
            list = getScoresByStudentId(Integer.parseInt(userStuId));
        } else {
            // 否则使用姓名查询
            list = getScoresByStudentName(studentName);
        }

        if (list.isEmpty()) {
            log.warn("未找到学生{}的成绩数据", studentName);
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(("未找到学生" + studentName + "的成绩数据").getBytes(StandardCharsets.UTF_8));
        }

        log.info("找到学生{}的成绩数据{}条", studentName, list.size());
        return generateExcelResponse(list, studentName + "的成绩.xlsx");
    }

    /**
     * 教师端导出成绩
     * @return
     */
    @PostMapping("/fileOutputAdmin")
    @Operation(summary = "教师导出所有成绩数据到文件")
    public ResponseEntity<byte[]> fileOutputStreamAdmin(HttpServletRequest request) {
        // 从请求头获取用户信息
        String userRole = request.getHeader("User-Role");
        log.info("收到导出请求 - 角色: {}", userRole);

        // 验证用户权限：只允许教师导出，禁止管理员
        if (!"teacher".equals(userRole)) {
            log.error("非教师用户请求导出所有成绩");
            return ResponseEntity.status(HttpStatus.FORBIDDEN)
                    .body("无权限访问，仅教师可导出成绩".getBytes(StandardCharsets.UTF_8));
        }

        log.info("教师开始导出所有成绩数据");
        List<Score> list = scoreService.list();
        return generateExcelResponse(list, "所有成绩.xlsx");
    }

    private ResponseEntity<byte[]> generateExcelResponse(List<Score> list, String filename) {
        if (list == null || list.isEmpty()) {
            log.error("成绩列表为空");
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
        }

        try {
            // 调用服务生成Excel字节数组
            byte[] excelBytes = scoreService.generateExcel(list);
            if (excelBytes == null || excelBytes.length == 0) {
                log.error("生成的Excel文件为空");
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
            }

            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            
            // 处理文件名编码
            try {
                String encodedFilename = java.net.URLEncoder.encode(filename, "UTF-8").replaceAll("\\+", "%20");
                headers.setContentDisposition(ContentDisposition.builder("attachment")
                    .filename(encodedFilename)
                    .build());
            } catch (Exception e) {
                log.warn("文件名编码失败，使用默认文件名", e);
                headers.setContentDisposition(ContentDisposition.builder("attachment")
                    .filename("score.xlsx")
                    .build());
            }
            
            headers.set("Access-Control-Expose-Headers", "Content-Disposition");
            log.info("文件导出成功: {}, 大小: {} bytes", filename, excelBytes.length);
            return new ResponseEntity<>(excelBytes, headers, HttpStatus.OK);
        } catch (Exception e) {
            log.error("文件导出失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }

    private List<Score> getScoresByStudentName(String name) {
        LambdaQueryWrapper<Score> scoreLambdaQueryWrapper = new LambdaQueryWrapper<>();
        scoreLambdaQueryWrapper.eq(Score::getStuName, name);
        return scoreService.list(scoreLambdaQueryWrapper);
    }

    private List<Score> getScoresByStudentId(Integer stuId) {
        LambdaQueryWrapper<Score> scoreLambdaQueryWrapper = new LambdaQueryWrapper<>();
        scoreLambdaQueryWrapper.eq(Score::getStuId, stuId);
        return scoreService.list(scoreLambdaQueryWrapper);
    }
}